package com.giveu.signature.common.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.Map;
import java.util.UUID;

import com.giveu.signature.bean.TemplateHtmlParam;
import com.giveu.signature.common.document.WpsUtil;
import com.giveu.signature.common.service.GenModelService;
import com.giveu.signature.common.util.FreeMarkUtil;
import com.giveu.signature.common.util.PdfSignUtil;

public class DocServiceImpl extends GenModelService {

	@Override
	public void genPdfOutputStream(OutputStream out, TemplateHtmlParam tm, Map<String, Object> map) throws Exception {
		String tempPath = System.getProperty("java.io.tmpdir")+File.separator+"template"+File.separator+tm.getTempKey().replace(":", "_")+tm.getFastPath().substring(tm.getFastPath().lastIndexOf("."));
		if(!new File(tempPath).exists()){
			new File(tempPath).createNewFile();
			com.giveu.common.utils.FileUtil.download(tm.getFastPath(), tempPath);
		}
		File doc = FreeMarkUtil.tempRenderDoc(tempPath, map);
		String outPath = System.getProperty("java.io.tmpdir")+File.separator+UUID.randomUUID()+".pdf";
		String outPath2 = System.getProperty("java.io.tmpdir")+File.separator+UUID.randomUUID()+".pdf";
		try {
			if(!new File(outPath).exists()){
				new File(outPath).createNewFile();
			}
			if(!new File(outPath2).exists()){
				new File(outPath2).createNewFile();
			}
			WpsUtil.word2PDF(doc.getAbsolutePath(), outPath);
			PdfSignUtil.sign(outPath, outPath2, tm);
			toOutputStream(out, outPath2);
		} catch (Exception e) {
			throw e;
		}finally {
			com.giveu.common.utils.FileUtil.deleteFile(outPath);
			com.giveu.common.utils.FileUtil.deleteFile(outPath2);
		}
		
	}
	
	public static void toOutputStream(OutputStream out,String filename) throws Exception {
		File file = new File(filename);
		if (!file.exists()) {
			throw new FileNotFoundException(filename);
		}
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(file));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
